/*
 * 敏感区域设置模块
 */
define("func/areaSetting",[
	"leaflet",
    "func/base",
    "control/panel",
    "plugins/ajaxpoll",
    
],function(L){
	L.ICT.Func.add("AreaSetting",{
		Class: L.Class.extend({
			initialize:function(){
				this.ictmap = L.ict.app.ictmap;
                this.dateUtil = L.ict.app.util.dateTime;
                this.dialog = L.ict.app.util.dialog;
                this.menu = L.ict.app.menu;
                this.menuid = "ict_menu_main_Area";
                this.config = Project_ParamConfig.AreaSettingCongig;
                this.ajax = new L.ICT.Ajax();
                this.data = [];
                this._container = null;
                this._popPanel = null;
                this._drawPopPanel = null;
                this._resultPopPanel = null;
                this._layer = null;
                this._layerType = null;
                 this._areaPanel = null;
                this._targetPanel = null;
                this._arealistData=null;
			},
			 start: function () {
                if(this._container || this._popPanel) {
                    return;
                }
                this.ictmap.OperateState.jktj = true;
                this._initUi();
                this._initEvts();
                this._container.find("input[type=radio]").eq(0).click();
                this._container.find("input[type=checkbox]").eq(0).click();
                this.menu.mainmenu.deactiveMenuExceptOne(this.menuid);
                this.menu.mainmenu.disableMenuExceptOne(this.menuid);
                this.menu.mainmenu.deactivePortInfo(); //退出港口菜单
            },
			 stop: function () {
                if(this._popPanel) { this._popPanel.remove(); }
                if(this.ictmap.map.hasLayer(this._layer)) {
                    this.ictmap.map.removeLayer(this._layer);
                }
                if(this.ictmap.map.hasLayer(this._locatelayer)){
                  this.ictmap.map.removeLayer(this._locatelayer);
                }
                if(this._drawPopPanel) {
                    this._drawPopPanel.remove();
                }
                if(this._resultPopPanel) {
                    this._resultPopPanel.close();
                }
                if(this._areaPanel) {
                    this._areaPanel.close()
                }
                this.ictmap.OperateState.jktj = false;
                this.ictmap.deactivate();
                this.menu.mainmenu.deactiveMenu(this.menuid);
                this.menu.mainmenu.enableMenu();
                this._container = null;
                this._popPanel = null;
                this._drawPopPanel = null;
                this._resultPopPanel = null;
                this._layer = null;
            },
            stopMenu: function () {
                this.ictmap.deactivate();
                this.menu.submenu.destory(this.menuid);
                this.menu.mainmenu.deactiveMenu(this.menuid);
            },
             _initUi: function () {
                var options = {
                    title: '敏感区域设置',
                    width: 300,
                    height: 200,
                    left: 200,
                    top: 200
                };
                var content = this._container = $(this.getContentHTML());
                options.contentHTML = content;
                var pop = this._popPanel = new L.ICT.PopPanel(options);
                pop.show();
                pop.on("popPanelRemove", function () {
                    this._popPanel = null;
                    this._container = null;
                    this.stop();
                }, this);
            },
              getContentHTML: function () {
                var html = [];
                html.push('<div class="areaSettingContainer">');
                html.push('<div class="area_title">');
                html.push('<div class="title_left">区域列表:</div>');
                html.push('<div class="title_right"><span class="delete">删除</span><span class="add">添加</span></div>')
                html.push('</div>');
                html.push('<div class="form-group" >');
                html.push(this.updateList());
                // html.push('<p><input type="checkbox" class="aisValue">区域二</p>');
                html.push('</div>');
                html.push('</div>');
                return html.join("");
            },

            updateList:function(){
            	// var self=this;
            	// var $container=self._container.find('.form-group');
            	// this._arealistData =[];
            	// console.log(1)
            	var url=this.config.areaListUrl;
            	var date={
            		type:255,
            		pageid:1,
            		pagecount:100,
            		show_status:1,
                };
            	this.ajax.post(url,date,true,this,function(res){
               		
                     if(res){
                        if(res.state !== 1){
                            this.dialog.alert("提示",res.msg.error);
                        }else{
                            // console.log(this);
                            this.data= res.msg.areas;
                            L.ict.app.localStorage.setItem("data",this.data);
                            // console.log(this.data);
                         	var html=[];
                            for(var i=0;i<this.data.length;i++){
                    		html.push('<p class="key" data-id='+this.data[i]['properties']['id']+'><input type="checkbox" name="areaSelect" class="aisValue"><a class="areaLocate" href="#">'+this.data[i]['properties']['name']+'</a></p>');
                    		
                    		}
                    		this._container.find(".form-group").html(html.join(""));
                    		this.locallayer();
                        }
                       
                    }
                  
             	
            	});
            	// console.log(this.data);
            	
            
            },
          
            _initEvts: function () {
                var self = this;
                var $msg =  self._container.find(".msg");
                var aisValue=self._container.find(".aisValue").val();

                //增加
                self._container.find(".add").on("click", function () {
                   
                   self.addArea() 
                 
                });
                self._container.find(".delete").on("click", function () {
                   var url=self.config.deleteAreaUrl;
                   var date={};
                   if(self.ictmap.map.hasLayer(self._layer)){
                      self.ictmap.map.removeLayer(self._layer);
                    }
                    if(self.ictmap.map.hasLayer(self._locatelayer)){
                      self.ictmap.map.removeLayer(self._locatelayer);
                    }
                   var $chks = self._container.find(".form-group input:checked");
                   
                    // $chks.each(function () {
                        // date.id = $chks.parent().attr("key");
                        // date.push(date.id);

                    // });
                    // 
                    var areas=[];
                  	for(var i=0;i<$chks.length;i++){
                  		// var id,
                  		areas.push($($chks[i].parentElement).data('id'));
                        // $chks[i].parent().remove();/**/
                  	}
                    // console.log($chks.parent());
                    // console.log(self._container.find(".form-group input:checked"));
                     date.areaIdArr=areas.join("~");
                    
//                    date.type=255;
//                     console.log(date);
                    self.ajax.post(url,date,true,this,function(res){
                        // if(res.state==1){
                        //     console.log(res.msg);
                        // }
                        if(res){
                            if(res.state !== 1){
                                self.dialog.alert("提示",res.msg.error);
                            }else{
                                // console.log(res.msg);
                                $chks.parent().remove();
                            }
                        }
                   });


                });
               
           	},
           	locallayer:function(){
                this._container.find(".areaLocate").on("click",function(e){
                	// console.log(1);
                	// console.log(this._arealistData);
                	var id = $(e.currentTarget).parent().data('id');

                	// console.log(id);
                    var chk = $(e.currentTarget).parent().find('input[name="areaSelect"]')[0].checked;
                    var areaInfo = this.getAreaDataById(id);
                    // console.log(areaInfo);
                    if (!areaInfo) return;
                    if(this.ictmap.map.hasLayer(this._locatelayer)){
                      this.ictmap.map.removeLayer(this._locatelayer);
                    }
                    // 定位图层
                    if (chk) {
                      this.ictmap.map.fitBounds(this._layer.getBounds());
                    } else {
                      this._locatelayer = L.ict.app.util.tool.convertGeoJsonToLeafletLayer(areaInfo);
                      this.ictmap.map.addLayer(this._locatelayer);
                      this.ictmap.map.fitBounds(this._locatelayer.getBounds());
                    }
                }.bind(this));
           	},
              getAreaDataById:function (id) {
            	  this._arealistData=L.ict.app.localStorage.getItem("data");
                if (this._arealistData && this._arealistData.length) {
                    for (var i = 0, len = this._arealistData.length; i < len; i++){
                        if (this._arealistData[i]['properties']['id'] === Number(id)) {
                            return this._arealistData[i];
                        }
                    }
                }
            },
            // 弹出添加区域窗口
            addArea: function(){
            	 var options = {
                    title: '添加区域',
                    width: 350,
                    height: 180,
                    top: 200,
                    left: 550,
                    contentHTML: this.getAreaHtml()
                };
                var pop = this._areaPanel = new L.ICT.PopPanel(options);
                pop.show();
                this._initAreaEvts();
                //窗口关闭事件
                this._areaPanel.on("popPanelRemove", function () {
                    if(this._drawPopPanel) {
                        this._drawPopPanel.remove();
                    }
                    if(this.ictmap.map.hasLayer(this._layer)) {
                        this.ictmap.map.removeLayer(this._layer);
                    }
                    this.stopMenu();
                    this._areaPanel = null;
                }, this);
                
                // this.ictmap.activate(L.ICT.MapMouseState.RECTANGLE, this._drawCallback, null, this);
            },
            getAreaHtml: function () {
                var html = [];
                html.push('<div class="addAreaContainer">');
                html.push('<div class="areaName">');
                html.push('<label>区域名称:<input type="text" class="areaNameText"></label><span class="drawRect">绘制</span>');
                html.push('</div>');
                html.push('<p class="msg"></p>');
                html.push('<div class="btnDiv"><button type="button" class="btn keep">保存</button></div>');
                html.push('</div>');
                return html.join('');
            },

            _initAreaEvts:function(){
            	var self=this; 
            	var $container = this._areaPanel.getContainer().find(".addAreaContainer");
            	var $areaNameText=$container.find(".areaNameText");
            	var $msg=$container.find(".msg");

            	$container.find(".drawRect").on("click",function(event){
            	
            		if(self.ictmap.map.hasLayer(self._layer)) {
                     self.ictmap.map.removeLayer(self._layer);
                    }
                    if(self._drawPopPanel) {
                        self._drawPopPanel.remove();
                    }
            	 	self.ictmap.activate(L.ICT.MapMouseState.RECTANGLE, self._drawCallback, null, self);
            	 });
            	$container.find(".keep").on("click",function(){

            		if($areaNameText.val()==""){
            			$msg.html("请输入区域名称!");
            			return;
            		}
            		if(self._layer==null){
            			$msg.html("请绘制区域!")
            			return;
            		}
            		var url=self.config.areaSettingUrl;
            		var data={};
            		// 获取矩形经纬度
            		var bounds=self._layer.getBounds();
            		data.ldlon = bounds.getSouthWest().lng; //左下经度
                    data.ldlat = bounds.getSouthWest().lat; //左下纬度
                    data.rulon = bounds.getNorthEast().lng;
                    data.rulat = bounds.getNorthEast().lat;
                    data.areaName=$areaNameText.val();
                    data.user='admin';
                    // console.log(data);
            		self.ajax.post(url,data,true,this,function(res,error){
                    	if(error) {
                            return;
                        }
                        if(res.state==1){
                            // $msg.html(res.msg.result);
                            self.updateList();
                            self._areaPanel.close();
                 			self.ictmap.map.removeLayer(self._layer);
                            
                        	return;
                        }
                        if(res.state==-2){
                        	$msg.html(res.msg.result);
                        	return;
                        
                        }
                        if(res.state==-1){
                        	$msg.html(res.msg.result);
                        	return;
                        }
                        
                    })


                    
                    
            	})
            },
           //绘图回调
            _drawCallback: function (e) {
                var layer = e.layer;
                var layerType = e.layerType;
                this.ictmap.map.addLayer(layer);
                // 检查范围是否越界
                var bounds = layer.getBounds();
                if (L.ict.app.util.tool.isLatLngsOutExtend(bounds)){
                    this.ictmap.map.removeLayer(layer);
                    L.ict.app.util.dialog.error('错误', '您绘制的区域超出合法范围！');
                    return;
                }
                //加图层
                this._layer = layer;
                // 弹出编辑框
                if(this._drawPopPanel) {
                    this._drawPopPanel.remove();
                }
                this._drawPopPanel = new L.ICT.DrawPopPanel(layer, layerType);
                this._drawPopPanel.on("popPanelRemove", function () {
                    this._drawPopPanel = null;
                }, this);
                this._drawPopPanel.show();
                //可编辑
                if(layer.editing) {
                    layer.editing.enable();
                    layer.on("edit", function (o) {
                        this._drawPopPanel.updateContent();
                    }, this);
                }
            },
      
		})
	})
})